import React, { useEffect, useState } from 'react';
import { Form, Button, DatePicker, Select, Space, Message, Popconfirm } from 'antd';
import moment from 'moment';
import _ from 'lodash';
import { connect } from 'umi';
import { useDebounceFn } from 'ahooks';

import { UploadOutlined, SyncOutlined } from '#/utils/antdIcons';
import { HttpCode } from '#/utils/contacts.js';

import { TRDefault, PageLoading } from '@/components';
import { TjSegmented, TjChart, TjStation, TjCollapse } from '@/pages/ETrade/components';
import { export_json_to_excel } from '@/utils/fileExport.js';
import { useRem } from '@/hooks';

import Title from './components/Title';
import BaseTable from './components/BaseTable';
import {
  getSpotResumeAnalysisData,
  postQueryProvinceList,
  querySpotResumeAnalysisOverall,
} from './services';
import {
  DIMENSION,
  DIMENSION96,
  DIMENSION_Month,
  PROVINCES,
  TYPE_OPTIONS,
  chartsMap,
  indexMap,
  chartsMap_subpage,
  Doubel_yAxis_title,
  Doubel_yAxis_serise,
  chartsMap_subpage_isSDN,
  DATETYPEOPTION,
} from './helper';
import {
  formatName,
  getFlagDataSource,
  formatJson,
  forMater,
  _getTotalStatementEnergyPrice,
  dealDataChoose,
} from '@/pages/ETrade/ProvinceSpotsReplayNew/utils';
import styles from '@/pages/ETrade/ProvinceSpotsReplayNew/index.less';
import { GSDay } from './components/GSDay/index.jsx';

let targetDate = [null, null];
// 当前日期大于当前月的2号
if (moment().diff(moment().startOf('month'), 'days') > 1) {
  targetDate = [moment().startOf('month'), moment()];
} else {
  targetDate = [
    moment().subtract(1, 'months').startOf('month'),
    moment().subtract(1, 'months').endOf('month'),
  ];
}

function ResumeAnalysis({ menuCode, buttonPermissions }) {
  const url = location.href;
  let queryUrlForm = {},
    hasUrlData = false;
  if (url.indexOf('?') != -1) {
    const [, value] = url.split('?');
    const [, urlValue] = value.split('=');
    queryUrlForm = JSON.parse(decodeURIComponent(urlValue));
    hasUrlData = !_.isEmpty(queryUrlForm);
  }
  let [spinning, setSpinning] = useState(true),
    [listLoading, setListLoading] = useState(true),
    [error, setError] = useState(''),
    [province, setProvince] = useState(''), // 切换省后选中的省份
    [regions, setRegions] = useState([]), // 全部省份
    [stations, setStations] = useState([]), // 全部场站（平铺）
    [regionsStations, setRegionsStations] = useState([]), // 对应省份场站（平铺）
    [stationTree, setStationTree] = useState([]), // 已选省份的场站树
    [realData, setRealData] = useState([]), // 记录echars数据
    [dimensionEnum, setDimensionEnum] = useState(hasUrlData ? queryUrlForm.dimensionEnum : 1), // 0-默认维度 1-切换维度
    [tag, setTag] = useState(hasUrlData ? queryUrlForm.tag : '1'), // 1-测算数据 2-结算数据
    [pointNum, setPointNum] = useState(hasUrlData ? queryUrlForm.pointNum : '96'), // 时点
    [sumaryData, setSumaryData] = useState([]), // 概括数据
    [tableData, setTableData] = useState({}), // 表格数据
    [choseValue, setChoseValue] = useState({}), // 当前展示的echarts数据
    [crumbsName, setCrumbsName] = useState(''), // echarts图表面包屑
    [visible, setVisible] = useState(false), // 控制大数据查询前提示
    [type, setType] = useState(hasUrlData ? queryUrlForm.type : 0), // 交易单元类型
    [queryForm, setQueryForm] = useState(hasUrlData ? queryUrlForm : {}), // 记录查询时用的表单，批量导出有参数依赖
    [dateType, setDateType] = useState(queryUrlForm?.dataType || 'days'),
    [dataTypeOptions, setDataTypeOptions] = useState([]); //日期查询类型配置项;

  let echarsData = [];
  const [form] = Form.useForm();
  useRem(1920);

  // 初始化交易单元类型
  useEffect(() => {
    if (hasUrlData && regionsStations.length) {
      onTypeChange(queryUrlForm.type);
    } else {
      onTypeChange(0);
    }
  }, [regionsStations]);

  useEffect(() => {
    moment.updateLocale('zh-cn', {
      week: { dow: 5, doy: 4 },
    });
    init();
    setChoseValue({ name: '合计', flag: '合计__parent' });
  }, []);

  useEffect(() => {
    getEcharsData(choseValue);
    let crum = '合计';
    // 处理合计时的面包屑-去掉合计
    if (choseValue.crumbsName) {
      const curmbsNameArr = choseValue.crumbsName.split('——');

      if (curmbsNameArr[0] === crum && curmbsNameArr.length > 1) {
        crum = curmbsNameArr.slice(1).join('——');
      } else if (dimensionEnum === 1 && hasUrlData && curmbsNameArr.length > 1) {
        // 96-场站维度的场站名称
        crum = curmbsNameArr[1];
      } else {
        crum = choseValue.crumbsName;
      }
    }
    setCrumbsName(crum);
  }, [tableData, choseValue]);

  /** handle data */
  async function init() {
    // 获取数据权限
    const res = await postQueryProvinceList(menuCode);
    if (res?.statusCode === HttpCode.SUCCESS) {
      initDataPower(res?.data);
    } else {
      setError(res?.message || '系统异常');
    }
    setSpinning(false);
  }

  // 点击查询表格数据
  async function _fetchFiles(postdata) {
    // 搜索
    setListLoading(true);
    setChoseValue({ name: '合计', flag: '合计__parent' });
    const res = await getSpotResumeAnalysisData(postdata).catch(() => setListLoading(false));
    if (res?.statusCode === HttpCode.SUCCESS) {
      const data = getFlagDataSource(res.data.tableData || [], postdata);
      setTableData({
        tableData: data,
        tableHead: res.data.tableHead,
      });
    }
    setListLoading(false);
  }

  // 点击查询概括数据
  async function _fetchSumarys(postdata, isMonth) {
    const params = { ...postdata };
    if (isMonth) {
      params.dimension = 'mon';
    }
    const res = await querySpotResumeAnalysisOverall(params).catch(() => {});
    if (res?.statusCode === HttpCode.SUCCESS) {
      if (province === PROVINCES.shandong) {
        res.data = res.data.filter((t) => t.label !== '现货考核');
      }
      setSumaryData(isMonth ? res.monData : res.data);
    }
  }

  //初始化表单参数+默认请求
  const initialValues = (_regions, _stations) => {
    let initData = {};
    if (hasUrlData) {
      initData = {
        regions: queryUrlForm.regions,
        type: queryUrlForm.type,
        stationIds: queryUrlForm.stationIds,
        dateType: queryUrlForm.dateType,
        dateRange: [
          moment(queryUrlForm.startDate, 'YYYY-MM-DD'),
          moment(queryUrlForm.endDate, 'YYYY-MM-DD'),
        ],
      };
    } else {
      const stationsIds = _stations
        .filter((item) => item._companyName == regions[0].value)
        ?.map((item) => item?.value || '');
      initData = {
        regions: _regions[0].value,
        type: 0,
        dateType: 'days',
        dateRange: targetDate,
        stationIds: stationsIds,
      };
    }

    onRegionChange(initData.regions);
    form.setFieldsValue(initData);
    onFinish(initData);
  };

  //重置
  const resetHanlder = () => {
    onRegionChange(hasUrlData ? queryUrlForm.regions : regions[0].value);
    initialValues(regions, stations);
  };

  function initDataPower(data = []) {
    // 处理数据权限
    if (!data) {
      return;
    }
    regions = [];
    stations = [];
    data.map((x) => {
      // 公司
      (x?.children || []).map((y) => {
        // 省份
        (y?.children || []).map((z) => {
          // 场站
          const temp = {
            _companyValue: x.value,
            _companyName: x.label,
            _regionCode: y.value,
            _regionName: y.label,
            _stationCode: z.value,
            _stationName: z.label,
            label: z.label,
            value: z.value,
            _type: z.type,
          };
          stations.push(temp);
        });
      });
    });
    regions = Object.keys(_.groupBy(stations, '_companyName')).map((_companyName) => ({
      label: _companyName,
      value: _companyName,
    }));
    setRegions(regions);
    setStations(stations);
    initialValues(regions, stations);
  }

  /** methods */
  // 切换省份
  const onRegionChange = (value) => {
    form.setFieldsValue({ stationIds: [], type: 0 });
    const _stations = stations.filter((x) => value.includes(x._companyName));
    setRegionsStations(_stations);
    setProvince(value);
    let _dateType;

    if (value === PROVINCES.gansu) {
      const _dateTypeOptions = DATETYPEOPTION.filter((t) =>
        buttonPermissions.find((_t) => _t.menuCode === t.menuCode),
      );
      setDataTypeOptions(_dateTypeOptions);
      _dateType = _dateTypeOptions[0]?.value;
    } else {
      _dateType = 'days';
    }

    onDateTypeChange(_dateType);
    form.setFieldsValue({ dateType: _dateType });
  };

  // 筛选交易单元类型
  const onTypeChange = (val) => {
    form.setFieldsValue({ stationIds: [] });
    setType(val);
    stationTree = [];
    const _groups = _.groupBy(regionsStations, '_regionName');
    let selectAll = [];
    for (const key in _groups) {
      const _newGroup = [];
      for (const k in _groups[key]) {
        if (!val) {
          // 全部交易单元
          _newGroup.push(_groups[key][k]);
        }
        if (_groups[key][k]._type === val) {
          // 选中的交易单元
          _newGroup.push(_groups[key][k]);
        }
      }
      selectAll = selectAll.concat(_newGroup.map((t) => t.value));
      if (_newGroup.length) {
        // 有交易单元的集团
        stationTree.push({
          title: key,
          key: Math.random(),
          children: _newGroup.map((item) => ({
            title: item._stationName,
            key: item._stationCode,
          })),
        });
      }
    }
    form.setFieldsValue({ stationIds: selectAll });
    if (!val) setStationTree(stationTree);
  };

  const onDateTypeChange = (e) => {
    form.setFieldsValue({
      dateRange: e === 'weeks' ? moment() : targetDate,
    });
    setDateType(e);
  };

  const onFinish = async (values) => {
    // 查询
    const _stations = stations.filter((x) => values.regions === x._companyName); // 根据stations中的数据取出省份，然后在取省份id
    const regionsName = _stations[0]._companyName;
    const isMonth = values.dateType === 'months';
    const params = {
      stationIds: values.stationIds.map((x) => x),
      provinceId: _stations?.[0]._companyValue, // 根据stations中的数据取出省份，然后在取省份id
      tag,
    };
    // 如果省份为山东省时默认为测算数据
    if (params.provinceId === '37') {
      params.tag = '1';
    }
    switch (values.dateType) {
      case 'months':
        params.startDate = moment(values.dateRange[0]).startOf('month').format('YYYY-MM-DD');
        params.endDate = moment(values.dateRange[1]).endOf('month').format('YYYY-MM-DD');
        break;
      case 'weeks':
        params.startDate = moment(values.dateRange).weekday(0).format('YYYY-MM-DD');
        params.endDate = moment(values.dateRange).weekday(6).format('YYYY-MM-DD');
        break;
      default:
        params.startDate = moment(values.dateRange[0]).format('YYYY-MM-DD');
        params.endDate = moment(values.dateRange[1]).format('YYYY-MM-DD');
    }
    if (queryUrlForm.dimension) {
      //子页面
      params.dimension = isMonth //按月查询
        ? dimensionEnum
          ? DIMENSION_Month['切换维度']
          : DIMENSION_Month['默认维度']
        : dimensionEnum
        ? DIMENSION96['切换维度']
        : DIMENSION96['默认维度'];
    } else {
      params.dimension = isMonth
        ? dimensionEnum
          ? DIMENSION_Month['切换维度']
          : DIMENSION_Month['默认维度']
        : dimensionEnum
        ? DIMENSION['切换维度']
        : DIMENSION['默认维度'];
    }

    const _groupIds = stations
      .filter((item) => item._companyName == values.regions)
      ?.map((item) => item?._regionCode || '');
    params.groupIds = [...new Set(_groupIds)];

    _fetchFiles({
      ...params,
      pointNum,
    });
    setQueryForm({
      ...params,
      dateType: values.dateType,
      regions: regionsName,
      dimensionEnum,
      pointNum,
      type,
    });
    _fetchSumarys(params, isMonth);
  };

  const getXaxis = (data, name) => {
    const newValue = [];
    data?.map((item) => {
      newValue.push(item[name]);
    });
    return newValue;
  };

  // 主页面取数逻辑
  const getTargetData = (data, name) => {
    data.map((item) => {
      if (item?.children?.length) {
        if (item.name === name) {
          echarsData.push(...item.children);
        } else {
          getTargetData(item.children, name);
        }
      } else {
        if (item.name === name) {
          echarsData.push(item);
        }
      }
    });
  };

  // 96点取数逻辑
  const getTargetData96 = (params) => {
    const { data, name, date, otherTradingUnit, flag, is96TradingUnit } = params;
    data.map((item) => {
      if (name === item.name) {
        echarsData.push(item);
      }
      if (item?.children && item?.children.length) {
        item?.children.map((y) => {
          if (name === y.name && flag === y.flag) {
            if (otherTradingUnit) {
              if (y?.children && y?.children.length) {
                echarsData.push(...y?.children);
              }
            } else {
              echarsData.push(y);
            }
          }
          if (name === y.name && flag === '合计__son') {
            echarsData.push(y);
          }
          if (name === y.name && is96TradingUnit && flag !== y.flag) {
            echarsData.push(y);
          }
          if (y?.children && y?.children.length) {
            y?.children.map((z) => {
              if (name === z.name && date && date === z.data.date) {
                echarsData.push(z);
              }
            });
          }
        });
      }
    });
  };

  const dealDataMap = (chartMap, chartData, dataMap) => {
    Object.values(chartMap).map((item) => {
      Object.entries(item).map((t) => {
        const _data = t[1].useData === false ? [] : [chartData];
        const _funcName = t[1].funcName;
        const _param = t[1]?.param || [];
        const dependentValue = dataMap?.[t[1]?.dependentValue];

        dataMap[t[0]] = dealDataChoose(_funcName, ..._data, ..._param, dependentValue);
      });
    });
  };

  // 获取echars图表数据
  const getEcharsData = (value) => {
    const data = tableData?.tableData || []; // 表格原始数据
    if (!queryForm.regions || !data.length) return;

    const { name, flag, date } = value;
    const dataMap = {};
    let isSDN = false; // 判断是否是场站-日期-96/24点数据
    let XAXIS; // 图标X轴方向数据

    /***主页面***/
    if (!hasUrlData) {
      switch (flag) {
        case `合计__parent`:
          echarsData = data.slice(1);
          XAXIS = getXaxis(echarsData, 'name');
        case `合计__son`: {
          // 合计下的日期
          const newData = data.slice(1) || [];
          getTargetData(newData, name);
          XAXIS = getXaxis(echarsData, 'flag').map((item) => {
            return item.split('__')[0];
          });
        }
        case `${name}__parent`: {
          // 其他交易单元
          const newData = data.slice(1) || [];
          getTargetData(newData, name);
          XAXIS = getXaxis(echarsData, 'name');
        }
      }
    } else {
      /***子页面***/
      if (flag === `合计__parent`) {
        echarsData = data.slice(1);
        XAXIS = getXaxis(echarsData, 'name');
      }
      // 合计下的日期
      else if (flag === `合计__son`) {
        const newData = data.slice(1) || [];
        getTargetData96({ data: newData, name, flag });
        XAXIS = getXaxis(echarsData, 'flag').map((item) => {
          return item.split('__')[0];
        });
      }
      // 合计下的日期下的96点
      else if (flag === `合计__grandson`) {
        const newData = data.slice(1) || [];
        getTargetData96({ data: newData, name, flag, date });
        XAXIS = getXaxis(echarsData, 'flag').map((item) => {
          return item.split('__')[0];
        });
      } else if (flag === `${name}__parent`) {
        if (queryForm?.dimensionEnum) {
          // 96点
          const newData = data.slice(1) || [];
          getTargetData96({ data: newData, name, flag, otherTradingUnit: true });
          XAXIS = getXaxis(echarsData[0]?.children, 'name');
          echarsData = echarsData[0]?.children;
        } else {
          // 其他交易单元
          const newData = data.slice(1) || [];
          getTargetData96({ data: newData, name });
          isSDN = true;
          XAXIS = getXaxis(echarsData[0]?.children[0]?.children, 'name');
        }
      } else if (flag && flag.split('__')[1] === `son`) {
        if (queryForm?.dimensionEnum) {
          // 96点下的交易单元
          const newData = data.slice(1) || [];
          getTargetData96({ data: newData, name, flag, is96TradingUnit: true });
          XAXIS = getXaxis(newData, 'name');
        } else {
          // 其他交易单元下的日期
          const newData = data.slice(1) || [];
          getTargetData96({ data: newData, name, flag, otherTradingUnit: true });
          XAXIS = getXaxis(echarsData, 'name');
        }
      }
    }
    if (!isSDN) {
      if (!hasUrlData) {
        new Set(Object.values(chartsMap[queryForm.regions]).flat()).map((t) => {
          if (t.includes('_')) return; //在下方计算
          dataMap[t] = forMater(echarsData, t);
        });
        //计算
        dataMap._averagePrice = _getTotalStatementEnergyPrice(
          echarsData,
          'totalStatementEnergyPrice',
        ); // 算术均价
        if (queryForm.regions === PROVINCES.shandong) {
          dataMap._provincialDayaheadStatementPriceaheadStatementPrice = forMater(
            echarsData,
            'provincialDayaheadStatementPrice',
          );
          dataMap._provincialRealtimeStatementPricetimeStatementPrice = forMater(
            echarsData,
            'provincialRealtimeStatementPrice',
          );
        }
      } else {
        dealDataMap(chartsMap_subpage[queryForm.regions], echarsData, dataMap);
      }
    } else {
      //子页面96|24点维度
      if (echarsData?.[0]?.children?.[0]?.children?.length) {
        dealDataMap(chartsMap_subpage_isSDN[queryForm.regions], echarsData[0]?.children, dataMap);
      }
    }
    setRealData({
      ...dataMap,
      XAXIS,
    });
  };

  /**图表配置*/
  const getChartOption = ([title, data], dataSource) => {
    const chartData = [],
      _yAxis = [{ type: 'value' }];
    dataSource.XAXIS.map((x, i) => {
      const temp = {};
      data.map((t) => {
        temp[t] = dataSource[t][i];
      });
      chartData.push({
        ...temp,
        XAXIS: x,
      });
    });
    if (Doubel_yAxis_title.includes(title)) {
      _yAxis.push({
        type: 'value',
        splitLine: { show: false },
      });
    }
    const _series = data.map((t) => {
      const { props, ...others } = _.cloneDeep(indexMap[t]);
      if (Doubel_yAxis_title.includes(title) && Doubel_yAxis_serise.includes(t)) {
        props.yAxisIndex = 1;
      }
      return {
        dataIndex: t,
        props,
        ...others,
      };
    });

    return {
      grid: { top: 20, left: 48, right: 36, bottom: 50 },
      series: _series,
      dataset: {
        source: chartData,
        dimensions: ['XAXIS', ...data],
      },
      tooltip: {},
      legend: {},
      xAxis: [{ type: 'category' }],
      yAxis: _yAxis,
    };
  };

  /** 山东图表数据配置 */

  const onChangeDimension = useDebounceFn(
    () => {
      echarsData = [];
      setDimensionEnum(Number(!dimensionEnum));
      form.submit();
    },
    { wait: 500 },
  );

  const onexport = () => {
    const hasSave =
      buttonPermissions.filter((item) => item.menuCode === 'ResumeAnalysisButtonWeb').length > 0;
    if (!hasSave) {
      return Message.info('请联系管理员获取相关权限');
    }
    let filename = '现货复盘分析';
    if (queryForm.regions) {
      filename = `${queryForm.regions}${queryForm.startDate.split('-').join('')}-${queryForm.endDate
        .split('-')
        .join('')}`;
    }
    const params = {
      header: ['维度'],
      data: [],
      filename,
    };
    const data = tableData?.tableData;
    const dataFalt = [];
    data.map((x) => {
      dataFalt.push(x);
      (x?.children || []).map((y) => {
        dataFalt.push(y);
        (y?.children || []).map((z) => {
          dataFalt.push(z);
        });
      });
    });
    const filterVal = ['name'];
    tableData.tableHead?.forEach((item, ind) => {
      params.header.push(item.name);
      filterVal.push(item.field);
    });
    params.data = formatJson(filterVal, dataFalt);
    export_json_to_excel(params);
  };

  const confirm = useDebounceFn(
    () => {
      setVisible(false);
      form.submit();
    },
    { wait: 500 },
  );

  const handleVisibleChange = (newVisible) => {
    if (!newVisible) {
      setVisible(newVisible);
      return;
    }
    // 判断是否需要进行查询按钮的二次确认框
    const { stationIds, dateRange } = form.getFieldsValue();
    if (stationIds && dateType !== 'weeks' && dateRange) {
      const days = dateRange[1].diff(dateRange[0], 'days') + 1;
      if (days * stationIds.length > 900 && hasUrlData) {
        //
        setVisible(newVisible);
      } else {
        confirm.run();
      }
    } else {
      confirm.run();
    }
  };

  /** render */
  const _getEchartsData = () => {
    const loopData = !hasUrlData
      ? Object.entries(chartsMap[queryForm.regions])
      : Object.entries(chartsMap_subpage[queryForm.regions]).map((t) => [t[0], Object.keys(t[1])]);
    return (
      <div className={styles.chartsRender}>
        {loopData.map((t, i) => {
          return (
            <div
              key={i}
              style={{
                height: `calc(${Math.floor(100 / loopData.length)}%)`,
                minHeight: 204,
              }}
            >
              <div className={styles.chartTitle}>{t[0]}</div>
              <div style={{ height: `calc(100% - 30px)` }}>
                <TjChart option={getChartOption(t, realData)} />
              </div>
            </div>
          );
        })}
      </div>
    );
  };

  const _getDateSelectEl = (v) => {
    switch (v) {
      case 'weeks':
        return <DatePicker style={{ width: 240 }} picker="week" />;
      case 'months':
        return (
          <DatePicker.RangePicker
            style={{ width: 240 }}
            picker="month"
            placeholder={['开始日期', '结束日期']}
            format={'YYYYMM'}
            separator="-"
          />
        );
      default:
        return (
          <DatePicker.RangePicker
            style={{ width: 240 }}
            placeholder={['开始日期', '结束日期']}
            format={'YYYYMMDD'}
            separator="-"
          />
        );
    }
  };

  const _renderForm = () => {
    return (
      <Form name="query-form" form={form} layout="inline" onFinish={onFinish}>
        <Form.Item name="regions" rules={[{ required: true, message: '省份不可为空!' }]}>
          <Select
            style={{ width: 200 }}
            options={regions}
            placeholder="省份"
            showSearch={true}
            showArrow={true}
            onChange={onRegionChange}
          />
        </Form.Item>
        <Form.Item name="type" rules={[{ required: true, message: '交易单元类型不可为空!' }]}>
          <Select
            style={{ width: 200 }}
            options={TYPE_OPTIONS}
            placeholder="交易单元类型"
            showArrow={true}
            onChange={onTypeChange}
          />
        </Form.Item>
        <Form.Item name="stationIds" rules={[{ required: true, message: '交易单元不可为空!' }]}>
          <TjStation options={stationTree} />
        </Form.Item>
        {province === PROVINCES.gansu && dataTypeOptions.length ? (
          <Form.Item name="dateType" rules={[{ required: true, message: '日期类型不可为空!' }]}>
            <TjSegmented
              style={{ width: 160 }}
              onChange={onDateTypeChange}
              options={dataTypeOptions}
            />
          </Form.Item>
        ) : (
          ''
        )}
        <Form.Item name="dateRange" rules={[{ required: true, message: '日期不可为空!' }]}>
          {_getDateSelectEl(dateType)}
        </Form.Item>
        <Popconfirm
          title="您选择的数据量较大，可能延长加载时间或引起页面崩溃，是否确认查询？"
          visible={visible}
          onVisibleChange={handleVisibleChange}
          onConfirm={() => confirm.run()}
          onCancel={() => setVisible(false)}
          okText="确认"
          cancelText="取消"
        >
          <Button className={styles.search} type="primary" htmlType="submit">
            查询
          </Button>
        </Popconfirm>
        <Button className={styles.search} onClick={resetHanlder} ghost>
          重置
        </Button>
      </Form>
    );
  };
  const _renderContent = () => {
    if (listLoading) return <PageLoading />;
    // if (error) return <TRDefault type="error" message={error} />;
    if (!tableData?.tableData?.length) return <TRDefault type={'empty'} />;

    const isGansu = queryForm?.regions == PROVINCES.gansu;
    const isMonth = queryForm.dateType === 'months';
    const isGanSuDay = isGansu && queryForm.dateType === 'days'; //甘肃日查询
    if (isGanSuDay) {
      return (
        <GSDay
          loading={listLoading}
          dataSource={tableData.tableData}
          dataHeader={tableData.tableHead}
          stations={stations}
          fetchData={() => {
            form.submit();
          }}
        />
      );
    }
    return (
      <>
        {!isGansu ? (
          <div className={styles.box}>
            <Title data={sumaryData} isMonth={isMonth} />
          </div>
        ) : (
          ''
        )}
        <div className={styles.content}>
          <TjCollapse
            left={
              <>
                <div className={styles.title}>{crumbsName}</div>
                {_getEchartsData()}
              </>
            }
            right={
              <>
                <div className={styles.date}>
                  <span>日期范围：</span>
                  {formatName(queryForm.startDate)}-{formatName(queryForm.endDate)}
                </div>
                <div className={styles.tableScroll}>
                  <BaseTable
                    tableData={tableData.tableData}
                    tableHead={tableData.tableHead}
                    stations={stations}
                    queryForm={queryForm}
                    queryUrlForm={queryUrlForm}
                    choseValue={(value) => setChoseValue(value)}
                  />
                </div>
              </>
            }
          />
        </div>
      </>
    );
  };
  if (spinning) return <PageLoading />;
  if (error) return <TRDefault type="error" message={error} />;
  if (!stations?.length) return <TRDefault type="lock" />;
  return (
    <div className={styles.container}>
      {/* 顶部工具栏 */}
      <div className={styles.toolbar}>
        <div>{_renderForm()}</div>
        <div>
          <Space size={16}>
            {hasUrlData && (province === PROVINCES.shanxi || province === PROVINCES.gansu) ? (
              <TjSegmented
                value={pointNum}
                options={[
                  { label: '24', value: '24' },
                  { label: '96', value: '96' },
                ]}
                onChange={(e) => {
                  setPointNum(e);
                  form.submit();
                }}
              />
            ) : null}
            <div className={styles.tag}>
              {/* 为山东省时取消数据切换 23.9.12*/}
              {province !== PROVINCES.shandong && (
                <TjSegmented
                  value={tag}
                  options={[
                    { label: '测算数据', value: '1' },
                    { label: '结算数据', value: '2' },
                  ]}
                  onChange={(e) => {
                    setTag(e);
                    form.submit();
                  }}
                />
              )}
            </div>
            <a className={styles.change} onClick={() => onChangeDimension.run()}>
              <SyncOutlined style={{ fontSize: 14, marginRight: 5 }} />
              切换维度
            </a>
            <a className={styles.export} onClick={onexport}>
              <UploadOutlined style={{ fontSize: 14, marginRight: 5 }} />
              导出
            </a>
          </Space>
        </div>
      </div>
      <div className={styles.contentAll}>{_renderContent()}</div>
    </div>
  );
}

export default connect(({ global }) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(ResumeAnalysis);
